// Copyright 2023 prestidigitator (as registered on forum.minetest.net)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mts

import (
    "io"
    "os"
    "strings"

    "github.com/spf13/cobra"

    "notabug.org/prestidigitator-mt/minetest-goutils/schematic"
)


var MTS2YAML = &cobra.Command{
    Use: "mts2yaml [--indent=n] [mstFile|-] [outFile|-]",

    Short: "Convert binary MTS schematic file to YAML.",

    Long: "Read a binary mintest MTS schematic file and dump the output in "+
          "human-readable YAML format.",

    Args: cobra.MaximumNArgs(2),

    ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) (
        []string, cobra.ShellCompDirective,
    ) {
        switch len(args) {
            case 0:
                return []string{"mts"}, cobra.ShellCompDirectiveFilterFileExt
            case 1:
                return nil, cobra.ShellCompDirectiveDefault
            default:
                return nil, cobra.ShellCompDirectiveNoFileComp
        }
    },

    RunE: func(cmd *cobra.Command, args []string) error {
        flags := cmd.Flags()
        nIndent, err := flags.GetInt("indent"); if err != nil { return err }

        // Don't confuse the user: from this point on, errors are runtime errors.
        cmd.SilenceUsage = true

        indent := "\t"
        if nIndent >= 0 { indent = strings.Repeat(" ", nIndent) }

        var ins io.Reader = os.Stdin
        if len(args) > 0 && args[0] != "-" {
            file, err := os.Open(args[0])
            if err != nil { return err }
            defer file.Close()
            ins = file
        }

        var outs io.Writer = os.Stdout
        if len(args) > 1 && args[1] != "-" {
            file, err := os.Create(args[1])
            if err != nil { return err }
            defer file.Close()
            outs = file
        }

        s, err := schematic.FromMTSStream(ins)
        if err != nil { return err }

        return s.WriteYAML(outs, indent)
    },
}

func init() {
    MTS2YAML.Flags().Int("indent", -1, "N spaces to indent (<0 for tabs)")
}
